<?php

namespace Virchow\MultipleDatabaseMigrate\Console\Commands;

use Illuminate\Console\Command;

class MultipleDatabaseMigrateCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'multiple_database_migrate';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'multiple database migration';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $definedConnections = array_keys(config('database.connections'));
        $connection = $this->choice('请选择要使用的数据库链接：', $definedConnections, 0);

        // 创建对应的目录
        $targetDir = database_path('migrations/' . $connection);
        if (!is_dir($targetDir)) {
            mkdir($targetDir, 0755);
        }

        $options = [
            '--path' => 'database/migrations/' . $connection,
        ];

        $action = $this->choice('请选择要进行的操作：', ['run', 'make', 'rollback', 'reset', 'refresh', 'status'], 0);
        switch ($action) {
            case "make":
                $migrationName = trim($this->ask('请输入迁移名称'));
                if (empty($migrationName)) {
                    $this->error("创建迁移时，必须输入迁移名称！！！");
                    return false;
                }
                $command = 'make:migration';
                $options['name'] = $migrationName;
                break;
            case 'run':
                $command = 'migrate';
                $options['--database'] = $connection;
                break;
            default:
                $command = 'migrate:' . $action;
                $options['--database'] = $connection;
        }

        $otherOptions = $this->ask('请输入附加参数[可选]');
        if ($otherOptions) {
            $otherOptions = explode(' ', $otherOptions);
            foreach ($otherOptions as $value) {
                $otherOption = explode('=', $value);
                if (count($otherOption) == 2) {
                    $options[$otherOption[0]] = $otherOption[1];
                }
            }
        }

        $logOptions = ' ';
        foreach ($options as $index => $item) {
            $logOptions .= $index . '=' . $item . ' ';
        }
        $this->info('最终生成的脚本命令为 ' . $command . $logOptions);

        // 执行最终的脚本
        $this->call($command, $options);
    }
}
